package com.ias.agdis_r.util;

import android.content.Context;

import com.ias.agdis_r.R;
import com.ias.agdis_r.bean.update.FTPServerInfoBean;
import com.ias.agdis_r.bean.user.UserInfoBean;
import com.ias.agdis_r.manager.DataBaseManager;
import com.ias.agdis_r.manager.JavaBeanManager;
import com.ias.agdis_r.manager.ServiceManage;
import com.ias.agdis_r.netservice.BaseService;
import com.ias.agdis_r.netservice.actions.PrivateNetService;
import com.ias.agdis_r.netservice.actions.PublicNetService;
import com.ias.agdis_r.netservice.actions.WifiNetService;
import com.ias.agdis_r.util.sdcard.WriteLog;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPReply;


/**
 * @author zhangsc
 * */
public class UpdateFile {
	
	public FTPClient ftpClient;
	private FTPServerInfoBean ftpServerInfo = null;
	private final String REMOTE_PATH = "";
	private static UpdateFile instance = null;
	private Context context = DataBaseManager.getInstance().getContext();
	
	public UpdateFile() {
		// 创建FTP CLIENT
		ftpClient = new FTPClient();
	}
	
	public static UpdateFile getInstance() {
		if (instance == null) {
			instance = new UpdateFile();
		}

		return instance;
	}
	/**
	 * 设置FTP配置
	 * 
	 * @param ftpServerInfo
	 */
	public void setFTPServerInfo(FTPServerInfoBean ftpServerInfo) {
		this.ftpServerInfo = ftpServerInfo;
	}
	
	public String getFtpIp(FTPServerInfoBean info)
	{
		BaseService usingService  = ServiceManage.getInstance().getUsingRestfulService();
		String url = "";
		if(usingService == null)
		{

		}
		else if(usingService.getClass().equals(PrivateNetService.class))
		{
			url = info.getPriip();
		}
		else if(usingService.getClass().equals(PublicNetService.class)||
				usingService.getClass().equals(WifiNetService.class))
		{
			url = info.getPubip();
		}
		
		return url;
	}
	
	/**
	 * 连接到FTP服务器
	 * 
	 * @param hostname
	 *            主机名
	 * @param port
	 *            端口
	 * @param username
	 *            用户名
	 * @param password
	 *            密码
	 * @return 是否连接成功
	 * @throws IOException
	 */
	public boolean ftpConnect() throws IOException {
		WriteLog.getInstance().writeLog(context.getString(R.string.UP_3));
		// 如果没有FTP配置信息
		if (ftpServerInfo == null) {
			return false;
		}
		String ip = getFtpIp(ftpServerInfo);
		int port = ftpServerInfo.getPort();
		WriteLog.getInstance().writeLog(context.getString(R.string.UP_9)+ip+":"+port);
		if(S.isEmpty(ip)&&port<=0){
			//没有可用网络
			return false;
		}
		ftpClient.connect(ip, port);
		if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
			if (ftpClient
					.login(ftpServerInfo.getUser(), ftpServerInfo.getPwd())) {
				// 下面三行代码必须要，而且不能改变编码格式，否则不能正确下载中文文件
				ftpClient.setControlEncoding("GBK");
				FTPClientConfig conf = new FTPClientConfig(
						FTPClientConfig.SYST_UNIX);
				conf.setServerLanguageCode("zh");
				// 设置被动模式
				ftpClient.enterLocalPassiveMode();
				// 设置以二进制方式传输
				ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
				WriteLog.getInstance().writeLog(context.getString(R.string.UP_4));
				return true;
			}
		}else{
			WriteLog.getInstance().writeLog(context.getString(R.string.UP_8)+ftpClient.getReplyCode());
			ftpDisconnect();
		}
		return false;
	}
	
	/**
	 * 上传文件
	 * @param filesNameList
	 *        本机文件名称列表
	 */
	public boolean upload(String filePath,String fileName){
		
		try {
			if(!ftpClient.isConnected()){
				ftpConnect();
			}
			//上传文件
			return upload(filePath,fileName,REMOTE_PATH);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			WriteLog.getInstance().writeLog(context.getString(R.string.UP_5));
			//ftp断开连接
			ftpDisconnect();
		}
		return false;
	}
	/**
	 * 上传文件
	 * @param fileNamePath
	 *            本机文件路径
	 * @param remotePath
	 *            远程文件路径
	 * @param fileName
	 *            文件名称
	 * @return    上传结果
	 */
	private boolean upload(String filePath,String fileName,String remotePath){
		 FileInputStream fis = null;  
		 boolean flag = false;
		 int returnCode = ftpClient.getReplyCode();
		 try {
			if (FTPReply.isPositiveCompletion(returnCode)) {// 如果登录成功  
				UserInfoBean userinfo = JavaBeanManager.getInstance().getUserinfo();
				if (null != userinfo) {
					//获取岗位标识
					String mfg = userinfo.getMfg();
					remotePath = remotePath + File.separator+ mfg;
				    ftpClient.makeDirectory(remotePath);  
				    // 设置上传目录  
				    ftpClient.changeWorkingDirectory(remotePath);  
				    ftpClient.setBufferSize(1024);  
				    ftpClient.setControlEncoding("UTF-8");  
				    ftpClient.enterLocalPassiveMode();  
				    WriteLog.getInstance().writeLog(context.getString(R.string.UP_1)+ filePath+context.getString(R.string.UU_20)+remotePath);
				    fis = new FileInputStream(filePath);  
				    ftpClient.storeFile(fileName, fis);  
				    flag = true;   //上传成功    
				}    
			 }else{
				 //断开连接
				 ftpDisconnect();
			 }
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			//找不到文件，认为文件已经上传成功
			flag = true;
			WriteLog.getInstance().writeLog(context.getString(R.string.UP_10)+filePath);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			WriteLog.getInstance().writeLog(context.getString(R.string.UP_6));
		}         
		 
		 return flag;  
	}
	
	
	/** */
	/**
	 * 断开与远程服务器的连接
	 * 
	 * @throws IOException
	 */
	public void ftpDisconnect() {
		if (ftpClient.isConnected()) {
			try {
				WriteLog.getInstance().writeLog(context.getString(R.string.UP_7));
				ftpClient.disconnect();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
